package leetcode.day;

// 14. 最长公共前缀
public class LongestCommonPrefix {
    public static void main(String[] args) {
        String[] data = {"flower","flow","flight"};
        System.out.println(longestCommonPrefix2(data));
    }

    public static String longestCommonPrefix(String[] strs) {
        if ("".equals(strs[0])) {
            return "";
        }
        int index = 0;
        boolean flag = true;
        StringBuilder res = new StringBuilder();
        for (; index < strs[0].length(); index++) {
            char c = strs[0].charAt(index);
            for (int i = 1; i < strs.length; i++) {
                if ((index < strs[i].length()) && (c != strs[i].charAt(index))) {
                    flag = false;
                    break;
                } else if (index >= strs[i].length()) {
                    flag = false;
                    break;
                }
            }
            if (flag) {
                res.append(c);
            }

        }
        return res.toString();
    }



    public static String longestCommonPrefix2(String[] strs) {

        if(strs.length==0) {
            return "";
        }
        //公共前缀比所有字符串都短，随便选一个先
        String s=strs[0];
        for (String string : strs) {
            while(!string.startsWith(s)){
                if(s.length()==0) {
                    return "";
                }
                //公共前缀不匹配就让它变短！
                s=s.substring(0,s.length()-1);
            }
        }
        return s;
    }
}
